<!--
 * @Author: 李小晴 2689279066@qq.com
 * @Date: 2023-02-03 09:42:24
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-11-07 03:02:41
 * @FilePath: \zhmc_pc\sys\src\views\Asset\Enclosure\Index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { ref, unref } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { ElTree, ElButton, ElLoading, ElMessageBox, ElTag } from 'element-plus'
import {
  spEnclosureListApi,
  spEnclosureAddAdminApi,
  spEnclosureEditApi,
  spEnclosureDelApi
} from '@/api/fa/enclosure'
import Assets from './components/Assets.vue'
import Record from './components/Record.vue'
import Edit from './components/Edit.vue'
import { Dialog } from '@/components/Dialog'
import { useRoute } from 'vue-router'
import { useI18n } from '@/hooks/web/useI18n'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const { t } = useI18n()
const { query } = useRoute()
const loading = ref({
  tree: false,
  save: false
})
const iconSize = 16
const iconColor = '#999'

const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const formData = ref<any>({})

const listData = ref<any>([])
const defaultProps = {
  children: 'children',
  label: 'name'
}

const deleteApi = async (id) => {
  const res = await spEnclosureDelApi({ id: id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    getList()
  }
}

const pasture_org_id = ref()
const dataInfo = ref({})
const action = (type: string, data: any) => {
  actionType.value = type

  switch (type) {
    case 'edit':
      dialogTitle.value = t('编辑菜单')
      formData.value = data
      if (formData.value.disp_order != null && typeof formData.value.disp_order === 'string') {
        formData.value.disp_order = Number(formData.value.disp_order)
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = data.pasture_org_name + '-资产列表'
      dialogVisible.value = true
      pasture_org_id.value = data.pasture_org_id
      dataInfo.value = data
      break
    case 'addChildrens':
      const [A, B] = data.split('-')
      const result = { A, B }
      dialogTitle.value = t('新增下级菜单')
      formData.value = {
        parent_id: '0',
        disp_order: 0,
        pasture_org_id: result.B,
        pasture_org_name: result.A
      }
      dialogVisible.value = true
      break
    case 'addChildren':
      dialogTitle.value = t('新增下级菜单')
      formData.value = {
        parent_id: data.id,
        disp_order: 0,
        pasture_org_id: data.pasture_org_id,
        pasture_org_name: data.pasture_org_name
      }
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = t('新增栏位')
      formData.value = {
        parent_id: '0',
        disp_order: 0,
        pasture_org_id: query.org_id ? query.org_id : '',
        pasture_org_name: query.org_name ? query.org_name : ''
      }
      dialogVisible.value = true
      break
    case 'delete':
      ElMessageBox.confirm('确定要删除这个栏位？', '删除栏位', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteApi(data.id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'record':
      dialogTitle.value = data.pasture_org_name + t('-记录')
      pasture_org_id.value = data.pasture_org_id
      formData.value = {
        parent_id: data.id,
        disp_order: 0
      }
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}
const groupedTree = ref()
const getList = async () => {
  const loadingMain = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await spEnclosureListApi({
    org_id: query.org_id
  })
    .catch(() => {})
    .finally(() => {
      setTimeout(() => {
        loadingMain.close()
      }, 500)
    })
  if (res) {
    listData.value = res.data
    groupedTree.value = listData.value.reduce((groups, node) => {
      const { pasture_org_name, pasture_org_id } = node
      const key = `${pasture_org_name}-${pasture_org_id}`
      if (!groups[key]) {
        groups[key] = []
        // groups[org_name] = []
      }
      groups[key].push(node)
      return groups
    }, {})
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const save = async (type: string) => {
  const edit = unref(editRef)
  await edit?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      // 点击后先让按钮loading
      loading.value.save = true
      const newData: any = await edit?.getFormData()
      const data = { ...edit.oldFormData, ...newData }
      data.my_dept_id = wsCache.get('userInfo').default_dept_id
      // data.org_id = query.org_id
      switch (type) {
        case 'edit':
          const res = await spEnclosureEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value.save = false
            })
          if (res) {
            dialogVisible.value = false
            getList()
          }
          break
        case 'addChildren':
        case 'add':
        case 'addChildrens':
          const addRes = await spEnclosureAddAdminApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value.save = false
            })
          if (addRes) {
            dialogVisible.value = false
            getList()
          }
          break
        default:
          console.log('未知类型')
      }
    }
  })
}

//初始化
const init = async () => {
  // 查询列表
  await getList()
}

init()
</script>

<template>
  <ContentWrap>
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add', {})">新增</ElButton>
    </div>

    <div class="custom-tree-container" v-for="(item, i) in groupedTree" :key="i">
      <span>
        <span style="font-weight: bold">{{ i }}</span>
        <span style="float: right">
          <a @click="action('addChildrens', i)">
            <Icon
              icon="carbon:add-filled"
              title="创建下级"
              :size="iconSize"
              class="cursor-pointer anticon"
              :color="iconColor"
            />
          </a>
        </span>
      </span>
      <ElTree
        :data="item"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template #default="{ node }">
          <span class="custom-tree-node">
            <span
              >{{ t(node.label) }}
              <ElTag
                :type="
                  node.data.type == '1' ? 'success' : node.data.type == '2' ? 'warning' : 'danger'
                "
              >
                {{ node.data.type == '1' ? '育肥' : node.data.type == '2' ? '低效' : '' }}
              </ElTag>
            </span>
            <span>
              <a @click="action('see', node.data)">
                <Icon
                  icon="ic:sharp-remove-red-eye"
                  title="查看"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <!-- <a @click="action('record', node.data)">
                <Icon
                  icon="bi:record-circle-fill"
                  title="记录"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a> -->
              <a @click="action('edit', node.data)">
                <Icon
                  icon="el:edit"
                  title="编辑"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('addChildren', node.data)">
                <Icon
                  icon="carbon:add-filled"
                  title="创建下级"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
              <a @click="action('delete', node.data)">
                <Icon
                  icon="fluent:delete-20-filled"
                  title="删除"
                  :size="iconSize"
                  class="cursor-pointer anticon"
                  :color="iconColor"
                />
              </a>
            </span>
          </span>
        </template>
      </ElTree>
    </div>
    <!-- </div> -->
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      ref="editRef"
      v-if="
        actionType == 'edit' ||
        actionType == 'add' ||
        actionType == 'addChildren' ||
        actionType == 'addChildrens'
      "
      :formData="formData"
    />
    <!-- :treeData="listData" -->
    <Record v-if="actionType == 'record'" :id="Number(pasture_org_id)" />
    <Assets v-if="actionType == 'see'" :dataInfo="dataInfo" :id="Number(pasture_org_id)" />
    <template #footer>
      <ElButton
        v-if="
          actionType == 'edit' ||
          actionType == 'add' ||
          actionType == 'addChildren' ||
          actionType == 'addChildrens'
        "
        type="primary"
        :loading="loading.save"
        @click="save(actionType)"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;

  a {
    padding: 0 3px;

    i {
      margin-top: 5px;
    }
  }
}
</style>
